package glossos.parsing;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.util.Iterator;

public class ReaderIterator implements Iterator<Reader> {
	private static Logger logger = Logger.getLogger("glossos.index");
	private File[] files;
	private Integer fileIndex;
	private ReaderFactory factory;

	public ReaderIterator(File file, FileFilter filter, ReaderFactory readerFactory) {
		this.factory = readerFactory;
		files = file.isDirectory() ? file.listFiles(filter) : (filter.accept(file) ? new File[]{file} : new File[0]);
		fileIndex = 0;
	}
	
	public boolean hasNext() {
		return fileIndex < files.length;
	}

	public Reader next() {
		try {
			File file = files[fileIndex++];
			logger.info("Processing file " + file);
			return factory.readerFor(file);
		} catch (FileNotFoundException e) {
			fileIndex++;
		}
		return null;
	}

	public void remove() {
		throw new UnsupportedOperationException("Removing of files not allowed.");		
	}
}
